package com.agg.persist.xml;

import com.agg.core.exception.EntityMapperException;
import com.agg.core.utils.Asserts;
import com.agg.core.utils.Beans;
import com.agg.core.utils.Strings;
import com.agg.persist.xml.dto.BuildDTO;
import com.agg.persist.xml.dto.TableColumnDTO;
import com.agg.persist.xml.mapping.EntityMapper;
import com.agg.persist.xml.mapping.Property;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class EntityMapperBuilder {
    private  Map<String, EntityMapper> entityMapperMapperMap;

    public EntityMapperBuilder(){
        entityMapperMapperMap=new HashMap<>();
    }

    protected final Log log = LogFactory.getLog(getClass());
    /**
     *  build join and  sqlmapper
     */
    public   EntityMapperBuilder add(BuildDTO dto){
        EntityMapper em= this.createEntityMapper(dto);
        this.entityMapperMapperMap.put(dto.getEmid(),em);
        return this;
    }

    public Map<String, EntityMapper> regist(){
        EntityMapperRegistry registrar= Beans.getBean(EntityMapperRegistry.class);
        if(this.entityMapperMapperMap.isEmpty()){
            String errMsg="mapper map  empty ";
            log.error(errMsg);
            throw  new EntityMapperException(errMsg);
        }
        registrar.build(this.entityMapperMapperMap);
        return entityMapperMapperMap;
    }

    private EntityMapper createEntityMapper(BuildDTO dto){
        EntityMapper em=new EntityMapper();
        em.setAlias(dto.getAlias());
        em.setId(dto.getEmid());
        em.setClazz("java.util.Map");
        em.setTable(dto.getTable());
        em.setProperties(new ArrayList<>());
        em.setJoins(dto.getJoins());
        List<TableColumnDTO> columns=dto.getColumns();
        for(TableColumnDTO col:columns){
            Property property=new Property();
            property.setColumn(col.getColName());
            property.setOwner(dto.getAlias());
            property.setName(Strings.toCamelCase(col.getColName(),"_"));
            String colAlias=col.getAlias();
            if(Asserts.isNullOrEmpty(colAlias)){
                colAlias=property.getName();
            }
            property.setAlias(colAlias);
            property.setQuery(col.getQueryType());
            property.setPrimaryKey(col.isPrimaryKey());
            em.getProperties().add(property);
        }
        return  em;
    }
}
